package com.company.project.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.project.common.utils.PasswordUtil;
import com.company.project.common.utils.RestUtil;
import com.company.project.mapper.InstitutionMapper;
import com.company.project.pojo.Rest;
import com.company.project.pojo.ServiceCode;
import com.company.project.common.utils.JwtUtil;
import com.company.project.pojo.institution.Institution;
import com.company.project.pojo.permission.PermissionDTO;
import com.company.project.pojo.rolePermission.RolePermission;
import com.company.project.pojo.user.User;
import com.company.project.pojo.user.UserDTO;
import com.company.project.pojo.user.UserVO;
import com.company.project.service.IInstitutionService;
import com.company.project.service.IPermissionService;
import com.company.project.service.IRolePermissionService;
import com.company.project.service.IUserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author 任建波
 * @since 2019-08-09
 */
@Api(value = "用户",tags = "用户")
@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private IUserService iUserService;
    @Autowired
    HttpServletRequest request;
    @Autowired
    private IPermissionService iPermissionService;
    @Autowired
    IRolePermissionService iRolePermissionService;
    @Autowired
    IInstitutionService iInstitutionService;

    @ApiOperation(value = "pc登录")
    @RequestMapping(value = "pcLogin", method = RequestMethod.POST)
    @ResponseBody
    public Rest<UserVO> pcLogin(String username, String password) throws Exception {
        if(username == null || password == null){
            return RestUtil.rest(ServiceCode.CODE_403, "账号和密码不能为空");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", username);
        queryWrapper.eq("password", PasswordUtil.generatePassword(password));
        queryWrapper.eq("is_delete", 0);

        User user = iUserService.getOne(queryWrapper);

        if (user == null){
            return RestUtil.rest(ServiceCode.CODE_401, "账号或密码不正确");
        }else {
            List<PermissionDTO> permissionDTOList = iPermissionService.getPermissionListByRoleId(user.getRoleId());

            Boolean loginPc = false;
            for ( PermissionDTO permissionDTO: permissionDTOList){
                if(permissionDTO.getCode().equals("login-pc")){
                    loginPc = true;
                    break;
                }
            }

            if(loginPc == false){
                return RestUtil.rest(ServiceCode.CODE_401, "你没有权限登录");
            }

            ObjectMapper objectMapper = new ObjectMapper();
            String subject = objectMapper.writeValueAsString(user);

            //24小时60分钟60秒1000毫秒
            String token = JwtUtil.createJWT("jwt唯一标识", "签发人", subject, 24*60*60*1000, user);
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            userVO.setToken(token);

            Institution institution = iInstitutionService.getById(user.getInstitutionId());
            userVO.setInstitutionName(institution.getName());

            return RestUtil.rest(ServiceCode.CODE_200, "成功" , userVO);
        }
    }

    @ApiOperation(value = "app登录")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="query", name = "username", value = "名称", required = true, dataType = "String"),
        @ApiImplicitParam(paramType="query", name = "password", value = "密码", required = true, dataType = "String"),
        @ApiImplicitParam(paramType="query", name = "pushId", value = "推送id", required = true, dataType = "String")
    })
    @RequestMapping(value = "appLogin", method = RequestMethod.POST)
    @ResponseBody
    public Rest<UserVO> appLogin(String username, String password, String pushId) throws Exception {
        if(username == null || password == null){
            return RestUtil.rest(ServiceCode.CODE_403, "账号和密码不能为空");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", username);
        queryWrapper.eq("password", PasswordUtil.generatePassword(password));
        queryWrapper.eq("is_delete", 0);

        User user = iUserService.getOne(queryWrapper);

        if (user == null){
            return RestUtil.rest(ServiceCode.CODE_401, "账号或密码不正确");
        }else {
            ObjectMapper objectMapper = new ObjectMapper();
            String subject = objectMapper.writeValueAsString(user);

            //30天24小时60分钟60秒1000毫秒
            String token = JwtUtil.createJWT("jwt唯一标识", "签发人", subject, 30*24*60*60*1000, user);
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            userVO.setToken(token);

            // 单位
            Institution institution = iInstitutionService.getById(user.getInstitutionId());
            userVO.setInstitutionName(institution.getName());
            userVO.setInstitutionType(institution.getType());

            //  权限
            QueryWrapper<RolePermission> rolePermissionQueryWrapper = new QueryWrapper<>();
            rolePermissionQueryWrapper.eq("role_id", user.getRoleId());
            List<PermissionDTO> permissionDTOList = iPermissionService.getPermissionListByRoleId(user.getRoleId());
            List<String> permissionCodeList = new ArrayList<>();
            for (PermissionDTO permissionDTO: permissionDTOList){
                permissionCodeList.add(permissionDTO.getCode());
            }
            userVO.setPermissionCodeList(permissionCodeList);

            // 推送id
            user.setPushId(pushId);
            iUserService.updateById(user);

            return RestUtil.rest(ServiceCode.CODE_200, "成功" , userVO);
        }
    }

    @ApiOperation(value = "退出")
    @RequestMapping(value = "logout", method = RequestMethod.POST)
    @ResponseBody
    public Rest logout() {
        return RestUtil.rest(ServiceCode.CODE_200, "成功" );
    }

    @ApiOperation(value = "获取用户列表")
    @RequestMapping(value = "getUserListPage", method = RequestMethod.GET)
    @ResponseBody
    public Rest getUserListPage(int currentPage, String name){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);

        IPage page = iUserService.getUserList(new Page(currentPage, 10));

        return RestUtil.rest(ServiceCode.CODE_200, "成功！！！" , page);
    }

    @ApiOperation(value = "获取用户")
    @RequestMapping(value = "getUserById", method = RequestMethod.GET)
    @ResponseBody
    public Rest getUserById(int id){
        User user = iUserService.getById(id);

        return RestUtil.rest(ServiceCode.CODE_200, "成功！！！" , user);
    }

    @ApiOperation(value = "获取登录用户")
    @RequestMapping(value = "getUserInfo", method = RequestMethod.GET)
    @ResponseBody
    public Rest getUserInfo(){
        Claims claims = JwtUtil.parseJWT(request.getHeader("token"));
        Integer user_id = claims.get("user_id", Integer.class);

        User user = iUserService.getById(user_id);

        return RestUtil.rest(ServiceCode.CODE_200, "成功" , user);
    }

    @ApiOperation(value = "添加用户")
    @RequestMapping(value = "addUser", method = RequestMethod.POST)
    @ResponseBody
    public Rest addUser(@RequestBody User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", user.getAccount());
        queryWrapper.eq("is_delete", 0);
        List<User> userList = iUserService.list(queryWrapper);
        if(userList.size() > 0){
            return RestUtil.rest(ServiceCode.CODE_403, "该账号已存在");
        }

        Claims claims = JwtUtil.parseJWT(request.getHeader("token"));
        Integer user_id = claims.get("user_id", Integer.class);

        user.setPassword(PasswordUtil.generatePassword("123456"));
        user.setInputUserId(user_id);

        iUserService.save(user);

        return RestUtil.rest(ServiceCode.CODE_200, "成功");
    }

    @ApiOperation(value = "修改用户")
    @RequestMapping(value = "updateUser", method = RequestMethod.POST)
    @ResponseBody
    public Rest updateUser(@RequestBody User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", user.getAccount());
        queryWrapper.eq("is_delete", 0);
        List<User> userList = iUserService.list(queryWrapper);
        for (int i=0; i<userList.size(); i++){
            if (userList.get(i).getId().equals(user.getId())){
                continue;
            }
            return RestUtil.rest(ServiceCode.CODE_403, "该账号已存在");
        }

        iUserService.updateById(user);

        return RestUtil.rest(ServiceCode.CODE_200, "成功！！！");
    }

    @ApiOperation(value = "删除用户")
    @RequestMapping(value = "deleteUser", method = RequestMethod.POST)
    @ResponseBody
    public Rest deleteUser(Integer id) {
        User user = new User();
        user.setId(id);
        user.setIsDelete(1);

        iUserService.updateById(user);

        return RestUtil.rest(ServiceCode.CODE_200, "成功！！！");
    }

    @ApiOperation(value = "修改用户密码")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="header", name = "token", value = "token", required = true, dataType = "String"),
        @ApiImplicitParam(paramType="query", name = "newPassword", value = "新密码", required = true, dataType = "String"),
        @ApiImplicitParam(paramType="query", name = "oldPassword", value = "旧密码", required = true, dataType = "String")
    })
    @RequestMapping(value = "updateUserPassword", method = RequestMethod.POST)
    @ResponseBody
    public Rest updateUserPassword(String newPassword, String oldPassword) {
        Claims claims = JwtUtil.parseJWT(request.getHeader("token"));
        Integer user_id = claims.get("user_id", Integer.class);

        User userById = iUserService.getById(user_id);
        if(PasswordUtil.generatePassword(oldPassword).equals(userById.getPassword())){
            User user = new User();
            user.setId(user_id);
            user.setPassword(PasswordUtil.generatePassword(newPassword));
            iUserService.updateById(user);

            return RestUtil.rest(ServiceCode.CODE_200, "成功");
        } else {
            return RestUtil.rest(ServiceCode.CODE_403, "旧密码不正确");
        }
    }

    @ApiOperation(value = "重置用户密码")
    @RequestMapping(value = "resetPassword", method = RequestMethod.POST)
    @ResponseBody
    public Rest resetPassword(Integer id, String password) {
        User user = new User();
        user.setId(id);
        user.setPassword(PasswordUtil.generatePassword(password));
        iUserService.updateById(user);

        return RestUtil.rest(ServiceCode.CODE_200, "成功！！！");
    }

}

